const path = require('path');
const fs = require('fs');
const ejs = require('ejs');

// 编译并生成对应模板 templateName模板名 data额外参数
const compile = (templateName, data) => {
    const templatePosition = `../templates/${templateName}`;
    // 获取模板完整路径
    const templatePath = path.resolve(__dirname, templatePosition);

    return new Promise((resolve, reject) => {
        ejs.renderFile(templatePath, { data }, {}, (err, result) => {
            if (err) {
                console.log(err);
                reject(err);
                return;
            }

            resolve(result);
        })
    })
}

const writeToFile = (path, content) => {
    // 判断path是否存在, 如果不存在, 创建对应的文件夹
    return fs.promises.writeFile(path, content);
}


// eg src/components/navbar/header
// 递归生成文件夹
const createDir = (dirPath) => {
    if (!fs.existsSync(dirPath)) {
        if (createDir(path.dirname(dirPath))) {
            fs.mkdirSync(dirPath);
            return true
        }
    } else {
        return true
    }

}

module.exports = {
    compile,
    writeToFile,
    createDir
}
